package client

import (
	"bytes"
	"fmt"
	"gitee.com/squbirreland/imgo/utils/try"
	"net"
)

type Client struct {
	serverIp   string
	serverPort int
	name       string
	conn       net.Conn
}

func NewClient(serverIp string, serverPort int) *Client {
	client := &Client{serverIp: serverIp, serverPort: serverPort}
	//获取连接
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	try.Throw(err)
	client.conn = conn
	//返回对象
	return client
}

func (c *Client) Start() {
	defer try.Close(c.conn)
	go c.listen()
	for {
		c.write(bytes.NewBufferString("hi").Bytes())
	}
}

func (c *Client) write(b []byte) {
	_, err := c.conn.Write(b)
	try.Throw(err)
	//now := time.Now()
	//fmt.Printf("[%d][%d]out< %s \n", now.Unix(), now.Nanosecond(), bytes.NewBuffer(b).String())
}

func (c *Client) listen() {
	for {
		tmp := make([]byte, 16, 32)
		read, err := c.conn.Read(tmp)
		try.Throw(err)
		_ = tmp[:read]
		//now := time.Now()
		//fmt.Printf("[%d][%d]in>> %s \n", now.Unix(), now.Nanosecond(), bytes.NewBuffer(data).String())
		//time.Sleep(time.Duration(2000))
	}
}
